#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");

    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));//如果连接成功，服务器会触发newConnection()信号
}
void Widget::newConnection_Slot()
{
    tcpSocket = tcpServer->nextPendingConnection();//获得已经连接的客户端的Socket
    QString ip = tcpSocket->peerAddress().toString();  //与客户端连接成功后，将客户端的（IP，端口）信息显示出来
    qint16 port = tcpSocket->peerPort();
    QString temp = QString("[%1:%2]:Connect Success!").arg(ip).arg(port);
    ui->receiveEdit->appendPlainText(temp);             //将信息显示在接收窗口
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget::readyRead_Slot()   //获取来自（客户端发来的）的数据
{
 /*
    QString buf;
    buf = tcpSocket->readAll();
    ui->receiveEdit->appendPlainText(buf);
*/
    //上下两种代码效果一样
    ui->receiveEdit->appendPlainText(tcpSocket->readAll());  //appendPlainText(),追加文本，不覆盖前面的数据
}
Widget::~Widget()
{
    delete ui;
}


void Widget::on_openBt_clicked()
{
      tcpServer->listen(QHostAddress::Any,ui->portEdit->text().toInt()); //开启监听，监听来自该端口所有人的连接
}

void Widget::on_closeBt_clicked()
{
    tcpSocket->close();
    tcpServer->close();    //关闭服务器
}



void Widget::on_sendBt_clicked()
{
    tcpSocket->write(ui->sendEdit->text().toUtf8().data());  //获取发送区的内容
}
